package com.knife.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.knife.news.logic.NewsService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.object.News;
import com.knife.news.object.Site;
import com.knife.news.object.Type;
import com.knife.util.CommUtil;

public class GenerateNewsTask extends BackGroundTask{
	/**
	 * 
	 */
	private static final long serialVersionUID = 6505431089540836246L;
	private String sid;
	
	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	SiteService siteDAO = SiteServiceImpl.getInstance();
	TypeService typeDAO = TypeServiceImpl.getInstance();
	NewsService newsDAO = NewsServiceImpl.getInstance();
	HTMLGenerater g;
	Site gsite = new Site();
	List<Type> gtypes=new ArrayList<Type>();
	List<News> allNews=new ArrayList<News>();
	Collection<Object> paras=new ArrayList<Object>();;
	Type gtype = new Type();
	News gnews;
	String sql;
	int rows;
	int pageSize;
	int totalPage;
	int nowPage;
	
	public void init(){
		name="generate news";
		sql = "k_display='1' and k_ispub='1' and k_type=?";
		gnews=newsDAO.getNewsById(sid);
		gtype=typeDAO.getTypeById(gnews.getType());
		if(gtype.getHtml()==1){
			paras.clear();
			paras.add(gnews.getType());
			int rows = newsDAO.getSum(1, "",gtype.getSite(),gtype.getId(), "", "", "",1);
			int pageSize = CommUtil.null2Int(gtype.getPagenum());// 每页20条
			totalPage = (int) Math.ceil((float) (rows)
				/ (float) (pageSize));// 计算页数
			total = totalPage+1;
		
			g = new HTMLGenerater(gtype.getSite());
		}
		//g.saveNewsToHtml(anews.getId());
		//System.out.println("system will generate:"+total+" channel");
	}
	
	protected void work() {
        try {
            Thread.sleep(sleep);
            //System.out.println("system running at:"+counter+"/"+gtypes.size());
            if(counter<totalPage){
            	//第一页已经在pub中生成，跳过
				nowPage=counter+1;
				if(nowPage==1){
					gnews.pub();
				}else{
					g.saveTypeListToHtml(gtype.getId(),sql, paras,nowPage,rows);
				}
				System.out.println("generate:"+gtype.getName()+":"+gtype.getHref(nowPage));
			}else{
				g.saveIndexToHtml();
			}
            counter++;
            sum += counter;
        } catch (InterruptedException e) {
            setRunning(false);
        }
    }
}
